import Taro ,{ Component } from '@tarojs/taro'
import { View , Text , Image , Canvas , Button} from '@tarojs/components'

import {
  AtFloatLayout
} from 'taro-ui'

import './jobDetail.scss'

import DataManager from '../../utils/DataManager.js'

import {base_url} from "../../network/config";


import location_icon from '../../image/ic_location.png'

import DetailToolBar from '../../component/DetailToolBar/detailToolBar.js'

import BasePage from "../basePage";
import {STORAGE_KEY} from "../../utils/const";

export default class jobDetail extends BasePage {
  config = {
    navigationBarTitleText: '招聘详情'
  }

  defaultProps = {
    jobId:'',
  }

  constructor() {
    super(...arguments)
    this.state = {
      companyInfo:'',
      jobDetailData:{},
      shareTempFilePath:'',
      shopHead:'',
      weixinCodeImage:'',
      screenWidth:Number,
      screenHeight:Number,
      shareShow:false,
    }
  }

  componentWillMount () {

    let systemInfo = Taro.getSystemInfoSync();
    this.setState({
      screenWidth:systemInfo.windowWidth,
      screenHeight:systemInfo.windowHeight,
    })

    this.jobId = this.$router.params.jobId;

    if (Taro.getStorageSync(STORAGE_KEY.SCENE)){
      this.jobId = Taro.getStorageSync(STORAGE_KEY.SCENE);
      Taro.setStorageSync(STORAGE_KEY.SCENE, ''); //  scene只使用一次  否则进入其他详情id会错乱
    }

    let shareUserId = this.$router.params.shareUserId;

    if (shareUserId && DataManager.getUserId() != shareUserId){ // 保证自己的userID 和分享人 的userId 不一致 否则会出现自己点自己分享的链接问题
      Taro.setStorageSync(STORAGE_KEY.SHARE_USER_ID , shareUserId);
    }

    this.loadJobDetail();
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  onShareAppMessage(options){
    console.log('---job-----options=======' + JSON.stringify(options))
    let _this = this;
    if (options.from == 'button'){
        // 转发成功
      let url = base_url + 'rest/user/share/save';
      Taro.request({
        url:url,
        data: {
          token:DataManager.getToken(),
          platform:'android_c',
          weixinId:DataManager.getWeiXinId(),
          loginChannel:'c',
          appId:'KC876D98B30UA40CJSNHI689FB33SDW',
          digest : 'dda484557c12febe48139d8f44051c13',
          id:_this.jobId,
          type:1,
        },
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        method: 'POST',
        success(res) {
        }
      })

      return {
        path: `/pages/job/jobDetail?jobId=` + _this.jobId + `&shareUserId=` + DataManager.getUserId()
      }
    }
  }

  loadJobDetail(){
    let _this = this;

    let url = base_url + 'stateless/pin/pinDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        id:_this.jobId
      },
      method: 'GET',
      success(res) {

        if (res.data.data && res.data.data.imageUrl){
          Taro.downloadFile({
            url:res.data.data.imageUrl,
            success: function (res2) {
              console.log(res2);
              _this.setState({
                shopHead:res2.tempFilePath
              })
            }
          })
        }

        _this.setState({
          jobDetailData:res.data.data,
        })
      }
    })
  }

  onSharePost = () =>{

    let pageData = 'pages/job/jobDetail';

    let _this = this;
    let url = base_url + 'stateless/weixin/code/weixinCodeDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        businessId:_this.jobId,
        businessType:3,
        page:pageData
      },
      method: 'GET',
      success(res) {
        console.log('weixinCode-----' + JSON.stringify(res))
        if (res.data && res.data.data && res.data.data.weixinCode){
          Taro.showLoading({
            title : '图片生成中...'
          });
          Taro.downloadFile({
            url:res.data.data.weixinCode,
            success: function (res2) {
              console.log('this.state.weixinCodeImag =======' +res2.tempFilePath)
              _this.setState({
                weixinCodeImage:res2.tempFilePath
              })
              setTimeout(function () {
                Taro.hideLoading();
                _this.createPoster();
              } , 200)
            },
          })
        }
      }
    })
  }

  createPoster(){

    let midX = (this.state.screenWidth - 80) / 2

    let that = this;
    const ctx = Taro.createCanvasContext('share')

    console.log('screen-----------' + this.state.screenWidth + '   ' + this.state.screenHeight)

    ctx.beginPath()
    ctx.setFillStyle('white')
    ctx.arc(10, 40 + 10, 10, Math.PI, Math.PI * 1.5)
    // border-top
    ctx.moveTo(10, 40)
    ctx.lineTo(this.state.screenWidth - 10, 40)
    ctx.lineTo(this.state.screenWidth, 40 + 10)
    // 右上角
    ctx.arc(this.state.screenWidth - 10, 40 + 10, 10, Math.PI * 1.5, Math.PI * 2)
    // border-right
    ctx.lineTo(this.state.screenWidth, 40 + 500 - 10)
    ctx.lineTo(this.state.screenWidth - 10, 40 + 500)
    // 右下角
    ctx.arc(this.state.screenWidth - 10, 40 + 500 - 10, 10, 0, Math.PI * 0.5)
    // border-bottom
    ctx.lineTo(10, 40 + 500)
    ctx.lineTo(0, 40 + 500 - 10)
    // 左下角
    ctx.arc(10, 40 + 500 - 10, 10, Math.PI * 0.5, Math.PI)
    // border-left
    ctx.lineTo(0, 40 + 10)
    ctx.lineTo(10, 40)
    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
    ctx.restore();
    ctx.draw(true)

    ctx.drawImage(this.state.weixinCodeImage ,20,350,100,100)
    ctx.draw(true);

    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.fillText('长按识别图中二维码',
      140, 380)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.fillText('查看招聘详情信息',
      140, 420)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(this.state.jobData.businessName,
      100, 270)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#436EEE')
    ctx.fillText(this.state.jobData.businessIntro,
      100, 300)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);


    let content = this.state.jobData.position + '    ' + this.state.jobData.peopleCount + '人    ' ;

    this.drawText(ctx,content.replace('\n',' ') ,20 , 80, 148 , this.state.screenWidth - 60 , '#ff4a43' , 18)

    let pay = '薪资：' + this.state.jobData.payScope;
    ctx.setFontSize(16);
    ctx.setFillStyle('#ff4a43');
    ctx.fillText(pay,
      20, 120)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.fillText(this.state.jobData.intro,
      20, 160)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    this.drawText(ctx,'地址：' + this.state.jobData.address.replace('\n',' ') ,20 , 200, 148 ,
      this.state.screenWidth - 60 , '#333333' ,14)

    // ctx.arc(50, 190, 30, 0, Math.PI * 2)
    // ctx.clip();
    ctx.drawImage(this.state.shopHead,20,250,60,60);
    ctx.restore();
    ctx.draw(true);

    setTimeout(function () {
      Taro.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 375,
        height: 667,
        canvasId: 'share',
        quality:1,
        success: function (res) {
          if (!res.tempFilePath) {
            Taro.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          } else {
            that.setState({
              shareTempFilePath: res.tempFilePath,
              shareShow:true
            })

            // let imageArray = [];
            // imageArray.push(res.tempFilePath);
            //
            // console.log('imagearray========' + imageArray[0])
            //
            // Taro.previewImage({
            //   urls:imageArray
            // })
          }
        }
      })
    } , 200)
  }

  drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth , color , fontSize) {
    ctx.setFontSize(fontSize);
    ctx.setFillStyle(color)

    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      console.log('line-------------' + lineWidth + '    ' + canvasWidth)
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 18; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  }

  saveSharePic = () =>{
    Taro.saveImageToPhotosAlbum({
      filePath: this.state.shareTempFilePath,
      success(res) {
        console.log("保存图片成功")
        console.log(res)
        Taro.showToast({
          title: '保存成功',
          duration: 2000
        })
      },
      fail(err) {
        console.log('失败')
        console.log(err)

        if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
          Taro.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
              } else {
                console.log('获取权限失败，给出不给权限就无法正常使用的提示')
              }
            }
          })
        }
      }
    })
  }

  onShareClose = () =>{
    this.setState({shareShow:false})
  }

  makePhoneCall = (phoneNumber , e) =>{
    Taro.makePhoneCall({
      phoneNumber : phoneNumber
    })
    e.stopPropagation()  // 拦截事件冒泡
  }

  onCheckLocation = () =>{
    const latitude =  this.state.jobDetailData.latitude
    const longitude =  this.state.jobDetailData.longitude
    Taro.openLocation({
      latitude,
      longitude,
      scale: 18
    })
  }

  render() {

    let jobData = this.state.jobDetailData;

    let peopleCount = jobData.peopleCount ? '招聘人数：' + jobData.peopleCount + '人' : ''

    console.log('-----jobId-----' + jobData.id)

    return (
      <View className='job-detail-container'>
        <View style='width:0px;height:0px;overflow:hidden;'>
          <Canvas canvasId='share' style='width:750px;height:1334px;position:fixed;left:9000px;'></Canvas>
        </View>
        <View className='job-detail-header-container-sub'>
          <View className='job-detail-header-container'>
            <View className='job-detail-header-row'>
              <Text className='job-detail-name'>{jobData.position}</Text>
              <Text className='job-detail-count'>{peopleCount}</Text>
            </View>
            <Text className='job-detail-intro'>{jobData.intro}</Text>
            <Text className='job-detail-salary'>{jobData.payScope}</Text>
            <View className='job-detail-thin-divider'></View>
            <View className='job-detail-address-container' onClick={this.onCheckLocation.bind(this)}>
              <Image style='width:20px;height:20px' src={location_icon}/>
              <Text className='job-detail-address'>{jobData.address}</Text>
            </View>
          </View>
        </View>
        <View className='job-detail-sub-title-container'>
          <Text className='job-detail-sub-title'>职位描述</Text>
          <View className='job-title-divider'></View>
        </View>
        <Text className='job-detail-content' style='color:#333333'>岗位职责</Text>
        <Text className='job-detail-content' style='margin-top:4px;color:#999999'>{jobData.postDuties}</Text>
        <Text className='job-detail-content' style='color:#333333'>岗位要求</Text>
        <Text className='job-detail-content' style='margin-top:4px;color:#999999'>{jobData.conditions}</Text>
        <View className='job-detail-sub-title-container'>
          <Text className='job-detail-sub-title'>公司信息</Text>
          <View className='job-title-divider'></View>
        </View>
        <View className='job-detail-company-main'>
          <Image style='width:60px;height:60px;margin:10px' src={jobData.imageUrl}></Image>
          <View className='job-detail-company-info'>
            <Text className='job-detail-intro' style='margin-top:0px;margin-left:0px'>{jobData.businessName}</Text>
            <Text className='job-detail-company-intro'>{jobData.businessIntro}</Text>
          </View>
        </View>
        <View className='job-detail-bottom-divider'></View>
        <DetailToolBar itemId={jobData.id} mobileNumber={jobData.businessMobile}
                       itemType={1} hasCollect={jobData.isCollect}/>
        <View className='job-detail-share'  onClick={this.onSharePost.bind(this)}>
          <Text className='job-detail-share-text'>分享</Text>
          <Text className='job-detail-share-text'>海报</Text>
        </View>
        <AtFloatLayout
          isOpened={this.state.shareShow}
          scrollY
          onClose={this.onShareClose.bind(this)}
          title='分享到朋友圈'
        >
          <View className='detail-share-container'>
            <Image className='detail-share-img' src={this.state.shareTempFilePath}></Image>
            <Button className='detail-share-btn-post' onClick={this.saveSharePic.bind(this)}>保存图片</Button>
            <Text className='detail-share-hint'>保存图片到手机后，您可到朋友圈分享该图片</Text>
          </View>
        </AtFloatLayout>
      </View>
    )
  }
}
